//
//  VRUserMoreInfoViewController.swift
//  VoiceRoom
//
//  Created by Rae on 2024/3/13.
//

import UIKit
import ZLPhotoBrowser

class VRUserMoreInfoViewController: VRBaseViewController, SAAnimationProtocol {

    private let backButton          = c_make_ex(UIButton.self)
        .image("return").end()
    private let skipButton         = c_make_ex(UIButton.self)
        .text("SKIP").color("#FFFC00").font(16.font_bold).end()
    private let titleLabel          = c_make_ex(UILabel.self)
        .color(.white).font(26.font_bold)
        .alignment(.center).text("Learn more about you").end()
    private let subLabel            = c_make_ex(UILabel.self)
        .color(.white.alpha(0.6)).font(16.font_medium)
        .alignment(.center).line(2)
        .text("Let your friends know it’s you. Everyone\ncan see your photos.").end()
    private let iconButton         = c_make_ex(UIButton.self)
        .image("welcome_avatar").corner(60).end()
    private let cameraImg          = c_make_ex(UIImageView.self)
        .image("welcome_camera").end()
    private let nameTextF          = c_make_ex(UITextField.self)
        .bgColor(.white.alpha(0.16)).corner(25).font(14.font_medium)
        .placeholder("Enter your name").color(.white).end()
    private let brithdayButton         = c_make_ex(UIButton.self)
        .image("welcome_go").corner(25)
        .bgColor(.white.alpha(0.16)).corner(25).end()
    private let brithdayLabel          = c_make_ex(UILabel.self)
        .color(.white.alpha(0.4)).font(16.font_medium)
        .text("Select birthday").end()
    private let nextButton         = c_make_ex(UIButton.self)
        .bgImage(UIImage.colorToImage(color: "#FFFC00".toColor))
        .bgImage(UIImage.colorToImage(color: "#FFFC00".toColor.alpha(0.2)),state: .disabled)
        .corner(25).font(18.font_bold).color(.white.alpha(0.2),state: .disabled)
        .text("Next").color(.black).end()
    private var birthdayString = ""
    private var iconImgUrl: String?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.subviews{
            backButton
            skipButton
            titleLabel
            subLabel
            iconButton
            cameraImg
            nameTextF
            brithdayButton.subviews{
                brithdayLabel
            }
            nextButton
        }
        
        backButton.top(.statusHeight + 2).leading(5).size(40)
        skipButton.trailing(15)
        skipButton.CenterY == backButton.CenterY
        titleLabel.top(.navi_height + 30).centerHorizontally()
        subLabel.centerHorizontally()
        subLabel.Top == titleLabel.Bottom + 10
        iconButton.size(120).centerHorizontally()
        iconButton.Top == subLabel.Bottom + 35
        cameraImg.size(32)
        cameraImg.Trailing == iconButton.Trailing
        cameraImg.Bottom == iconButton.Bottom
        nameTextF.width(310).height(50).centerHorizontally()
        nameTextF.Top == iconButton.Bottom + 30
        brithdayButton.width(310).height(50).centerHorizontally()
        brithdayButton.Top == nameTextF.Bottom + 20
        nextButton.width(310).height(50).bottom(.safe_bottom + 55).centerHorizontally()
        brithdayLabel.leading(20).centerVertically()
        
        nameTextF.style { v in
            v.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
            v.placehold(.white.alpha(0.4), font: 16.font_medium)
            let leftV = UIView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
            v.leftView = leftV
            v.leftViewMode = .always
        }
        brithdayButton.contentHorizontalAlignment = .right
        nextButton.isEnabled = false
        
        iconButton.addTarget(self, action: #selector(clickIconButton), for: .touchUpInside)
        skipButton.addTarget(self, action: #selector(clickSkipButton), for: .touchUpInside)
        nextButton.addTarget(self, action: #selector(clickNextButton), for: .touchUpInside)
        brithdayButton.addTarget(self, action: #selector(clickBrithdayButton), for: .touchUpInside)
        
        UserDefaultsManager.setInt(2, forKey: .currentPage)
    }
    
    // 实时监听文本变化的方法
    @objc func textFieldDidChange(_ textField: UITextField) {
        if let text = textField.text {
            updateNextState()
        }
    }
    
    private func updateNextState(){
        
        if nameTextF.text?.count ?? 0 > 0 && birthdayString.count > 0 {
            nextButton.isEnabled = true
        }else{
            nextButton.isEnabled = false
        }
    }
}


//MARK: action
extension VRUserMoreInfoViewController {
    
    @objc private func clickIconButton(){
        //打开相册
        ZLPhotoConfiguration.default()
            .allowSelectVideo(false)
        let ps = ZLPhotoPreviewSheet()
        ps.selectImageBlock = { [weak self] results, isOriginal in
            ToastTool.show()
            let image = results.first?.image
            self?.iconButton.setImage(image, for: .normal)
            RT.uploadCoverImage(file: (self?.imageToBase64String(image: image!))!) { [weak self] (dict) in
                ToastTool.dismiss()
                self?.iconImgUrl = dict.url!
            }
        }
        ps.showPhotoLibrary(sender: self)
    }
    
    @objc private func clickBrithdayButton(){

        let chooseView = VRChooseBrithdayView()
        chooseView.didChooseCompletion = { [weak self] dateStr in
            self?.birthdayString = dateStr
            self?.brithdayLabel.text = dateStr
            self?.brithdayLabel.textColor = .white
            self?.updateNextState()
        }
        saAnimate.animation(show: chooseView)
    }
    
    @objc private func clickSkipButton(){
        
        ToastTool.show()
        let image = UIImage(named: "welcome_avatar")
        RT.uploadCoverImage(file: (self.imageToBase64String(image: image!))!) { dict in
            let imgUrl = dict.url!
            let dict = ["headImage":imgUrl,"userId":USEINFOMODEL.id,"name":"Voicer"]
            UserDefaultsManager.removeForKey(forKey: .currentPage)
            RT.initUserInfoWith(paraInfo: dict as [String : Any]) { info in
                UIApplication.window?.rootViewController = VRTabBarViewController()
            }
        }
    }
    
    @objc private func clickNextButton(){
        
        if let img = iconImgUrl {
            let dict = ["headImage":img,"name":nameTextF.text ?? "","userId":USEINFOMODEL.id ?? "", "birthday":birthdayString] as [String : Any]
            RT.initUserInfoWith(paraInfo: dict as [String : Any]) { info in
                ToastTool.dismiss()
                UIApplication.window?.rootViewController = VRTabBarViewController()
            }
        }else {
            let image = UIImage(named: "welcome_avatar")
            RT.uploadCoverImage(file: (self.imageToBase64String(image: image!))!) { dict in
                let imgUrl = dict.url!
                let dict = ["headImage":imgUrl,"userId":USEINFOMODEL.id ?? "","name":self.nameTextF.text ?? "", "birthday":self.birthdayString]
                UserDefaultsManager.removeForKey(forKey: .currentPage)
                RT.initUserInfoWith(paraInfo: dict as [String : Any]) { info in
                    UIApplication.window?.rootViewController = VRTabBarViewController()
                }
            }
        }
    }
}
